import re
import time

import requests
from lxml import etree


def del_materials(cookies):
    JSESSIONID = cookies.get("JSESSIONID", "")
    insert_cookie = cookies.get("insert_cookie", "")
    AD_VALUE = cookies.get("AD_VALUE", "")
    del_ok = False
    # 当前年份
    now_year = time.strftime("%Y", time.localtime())
    headers = {
        "Connection": "Close",
        "Cookie": f"JSESSIONID={JSESSIONID}; insert_cookie={insert_cookie}; AD_VALUE={AD_VALUE}",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36"
    }
    # 查询材料列表  跳转连接
    url = 'https://slb.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/list.do'
    select_list_rst = requests.get(url=url, headers=headers, allow_redirects=False)
    ad_value_dict = requests.utils.dict_from_cookiejar(select_list_rst.cookies)
    ad_value = ad_value_dict.get("AD_VALUE", "")
    if ad_value != "":
        headers = {
            "Connection": "Close",
            "Cookie": f"JSESSIONID={JSESSIONID}; insert_cookie={insert_cookie}; AD_VALUE={ad_value}",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36"
        }
    url = 'https://slb.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/list.do?ad_check=1'
    select_list_rst = requests.get(url=url, headers=headers)
    if select_list_rst.status_code == 200:
        tree = etree.HTML(select_list_rst.text)
        materials_list = tree.xpath("//form[@id='DataInnocom_list']/div[2]/div[2]/div[2]/table/tbody/tr")
        for materials in materials_list:
            materials_year = ''.join(materials.xpath("./td[1]/text()"))
            materials_status = ''.join(materials.xpath("./td[4]/text()"))
            materials_del_url = ''.join(materials.xpath("./td[5]/a[2]/@href"))
            if materials_year == now_year:
                if '申报材料填写中' in materials_status:
                    re_str = """'(.*)'"""
                    url = 'https://slb.chinatorch.org.cn' + ''.join(re.findall(re_str, materials_del_url))
                    del_requests_rst = requests.get(url=url, headers=headers)
                    s = 'var alertMessage = "删除成功";'
                    if s in del_requests_rst.text:
                        print("删除材料")
                    else:
                        ''.join(re.findall("""var alertMessage = "(.*)";""", del_requests_rst.text))
                    del_ok = True
                else:
                    print(materials_status)
        if not del_ok:
            print("未找到当前年份材料")

    else:
        print(select_list_rst.text)
        print(select_list_rst.status_code)
        print(select_list_rst)


if __name__ == '__main__':
    cookies = {
        'JSESSIONID': '361E0CDA89595AF86874D19A87A086FD',
        'insert_cookie': '48043037',
        'AD_VALUE': '9d40f918'
    }
    del_materials(cookies=cookies)